<template>
  <view class="stock-container">
    <!-- 搜索表单 -->
    <view class="search-form">
<!--      <view class="form-item">-->
<!--        <text class="label">物料编号<text class="required">*</text></text>-->
<!--        <input -->
<!--          v-model="queryParams.materialCode" -->
<!--          class="input" -->
<!--          type="text" -->
<!--          placeholder="请输入物料编号"-->
<!--        />-->
<!--      </view>-->
<!--      -->
<!--      <view class="form-item">-->
<!--        <text class="label">箱号</text>-->
<!--        <input -->
<!--          v-model="queryParams.boxId" -->
<!--          class="input" -->
<!--          type="text" -->
<!--          placeholder="请输入箱号"-->
<!--        />-->
<!--      </view>-->

      <view class="form-item">
        <text class="label">库位</text>
        <view class="input-wrapper">
          <input
            v-model="queryParams.fmloc"
            class="input"
            type="text"
            placeholder="请输入库位"
            @clear="handleClear"
          />
          <text 
            v-if="queryParams.fmloc" 
            class="clear-btn" 
            @click="handleClear"
          >×</text>
        </view>
      </view>

<!--      <view class="form-item">-->
<!--        <text class="label">批次号</text>-->
<!--        <input -->
<!--          v-model="queryParams.batchNumber" -->
<!--          class="input" -->
<!--          type="text" -->
<!--          placeholder="请输入批次号"-->
<!--        />-->
<!--      </view>-->
<!--      -->
<!--      <view class="form-item">-->
<!--        <text class="label">托盘号</text>-->
<!--        <input -->
<!--          v-model="queryParams.pln" -->
<!--          class="input" -->
<!--          type="text" -->
<!--          placeholder="请输入托盘号"-->
<!--        />-->
<!--      </view>-->
<!--      -->
<!--      <view class="form-item">-->
<!--        <text class="label">站点</text>-->
<!--        <input -->
<!--          v-model="queryParams.stationCode" -->
<!--          class="input" -->
<!--          type="text" -->
<!--          placeholder="请输入站点"-->
<!--        />-->
<!--      </view>-->

      <view class="btn-group">
        <button @click="handleCL" class="btn btn-default":disabled="loading2">
          <text v-if="loading2" class="cuIcon-loading2 iconfont-spin"></text>
          {{ loading2 ? '处理中...' : '异常处理' }}
        </button>
        <button @click="handleQuery" class="btn btn-primary" :disabled="loading">
          <text v-if="loading" class="cuIcon-loading2 iconfont-spin"></text>
          {{ loading ? '查询中...' : '查询' }}
        </button>
      </view>
    </view>

    <!-- 查询结果列表 -->
    <view class="stock-list" v-if="stockList.length > 0">
      <!-- 头部信息 -->
      <view class="stock-header">
        <text class="material-code">物料编号：{{ (stockList[0] && stockList[0].partCode) || '-' }}</text>
        <text class="quantity">{{ stockList.length }} 件</text>
      </view>
      
      <!-- 表格 -->
      <view class="stock-table">
        <!-- 表头 -->
        <view class="table-header">
          <view class="table-cell header-cell barcode-col">条码</view>
<!--          <view class="table-cell header-cell material-col">物料编号</view>-->
          <view class="table-cell header-cell task-col">入库任务号</view>
          <view class="table-cell header-cell location-col">库位</view>
          <view class="table-cell header-cell action-col">操作</view>
        </view>
        
        <!-- 表格内容 -->
        <view class="table-body">
          <view class="table-row" v-for="(item, index) in stockList" :key="index">
            <view class="table-cell barcode-col">{{ item.barcodeNo || '-' }}</view>
<!--            <view class="table-cell material-col">{{ item.partCode || '-' }}</view>-->
            <view class="table-cell task-col">{{ item.taskCode || '-' }}</view>
            <view class="table-cell location-col">{{ item.stockId || '-' }}</view>
            <view class="table-cell action-col">
              <button class="action-btn off-shelf-btn" @click="handleOffShelf(item, index)">
                下架
              </button>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 空状态 -->
    <view class="empty-state" v-else-if="!loading">
      <text class="empty-text">暂无数据</text>
    </view>
  </view>
</template>

<script>
import { queryStockList, xjStock ,CLStockList} from "@/api/system/stock";

var main, receiver, filter;

export default {
  data() {
    return {
      // 查询参数
      queryParams: {
        materialCode: '', // 物料编号
        boxId: '',       // 箱号
        fmloc: '',       // 库位
        batchNumber: '',  // 批次号
        pln: '',         // 托盘号
        stationCode: '', // 站点
        location:''
      },
      // 库存列表数据
      stockList: [],
      // 加载状态
      loading: false,
      loading2: false
    }
  },

  onLoad() {
    this.initScan();
  },

  onShow() {
    this.startScan();
  },

  onHide() {
    this.stopScan();
  },

  onUnload() {
    this.stopScan();
  },

  methods: {
    initScan() {
      let _this = this;
      /* #ifdef APP-PLUS */
      main = plus.android.runtimeMainActivity();
      var IntentFilter = plus.android.importClass('android.content.IntentFilter');
      filter = new IntentFilter();
      filter.addAction("com.service.scanner.data")
      receiver = plus.android.implements('io.dcloud.feature.internal.reflect.BroadcastReceiver', {
        onReceive: function (context, intent) {
          plus.android.importClass(intent);
          let code = intent.getStringExtra("ScanCode");
          console.log(code)
          _this.handleScanResult(code);
        }
      });
      /* #endif */
    },

    startScan() {
      /* #ifdef APP-PLUS */
      main.registerReceiver(receiver, filter);
      /* #endif */
    },

    stopScan() {
      /* #ifdef APP-PLUS */
      main.unregisterReceiver(receiver);
      /* #endif */
    },
    // 下架处理
    handleOffShelf(item, index) {
      this.$modal.confirm('确定要下架该物料吗？').then(() => {
        // 调用下架API
        const offShelfData = {
          barcodeNo: item.barcodeNo,
          // 根据后端需要的参数添加其他字段
        };
        
        // 显示加载状态
        this.loading = true;
        
        xjStock(offShelfData)
          .then(res => {
            if (res.code === 200) {
              console.log('下架物料成功:', item.barcodeNo);
              // 从列表中移除该项
              this.stockList.splice(index, 1);
              this.$modal.msgSuccess('下架成功');
            } else {
              this.$modal.msgError(res.msg || '下架失败');
            }
          })
          .catch(error => {
            console.error('下架失败:', error);
            this.$modal.msgError('下架失败，请稍后重试');
          })
          .finally(() => {
            this.loading = false;
          });
      }).catch(() => {
        // 用户取消操作
      });
    },


    // 处理扫码结果
    handleScanResult(code) {
      // 判断扫码内容类型
      if (code.startsWith('M')) {
        // 物料编号格式
        this.queryParams.materialCode = code.substring(1);
      } else if (code.startsWith('B')) {
        // 箱号格式
        this.queryParams.boxId = code.substring(1);
      } else if (code.startsWith('L')) {
        // 库位格式
        this.queryParams.fmloc = code.substring(1);
      } else if (code.startsWith('BN')) {
        // 批次号格式
        this.queryParams.batchNumber = code.substring(2);
      } else {
        // 默认当作物料编号处理
        this.queryParams.materialCode = code;
      }
      // 立即查询
      this.handleQuery();
    },

    // 查询按钮点击事件
    handleQuery() {
      if (this.loading) return;

      if (!this.queryParams.fmloc) {
        this.$modal.msgError('请输入库位');
        return;
      }

      this.loading = true;
      this.getList();
    },
    handleCL(){
      if (this.loading2) return;

      if (!this.queryParams.fmloc) {
        this.$modal.msgError('请输入库位');
        return;
      }

      this.loading2 = true;
      this.getList1();
    },

    // 清空库位输入框
    handleClear() {
      this.queryParams.fmloc = '';
    },

    // 重置按钮点击事件
    handleReset() {
      this.queryParams = {
        materialCode: '',
        boxId: '',
        fmloc: '',
        batchNumber: '',
      }
      this.stockList = [];
    },

    // 获取库存列表数据
    getList() {
      queryStockList(this.queryParams)
        .then(res => {
          if (res.code === 200) {
            // 为每个项目添加expanded属性
            this.stockList = res.rows.map(item => {
              return {
                ...item,
                expanded: false
              }
            });
          } else {
            this.$modal.msgError(res.msg || '查询失败');
          }
        })
        .catch(error => {
          console.error('查询库存失败:', error);
          this.$modal.msgError('查询失败，请稍后重试');
        })
        .finally(() => {
          this.loading = false;
        });
    },

    getList1() {
      CLStockList(this.queryParams)
          .then(res => {
            if (res.code === 200) {
              // 为每个项目添加expanded属性
              this.$modal.msgSuccess(res.msg || '处理成功');
            } else {
              this.$modal.msgError(res.msg || '处理失败');
            }
          })
          .catch(error => {
            console.error('查询库存失败:', error);
            this.$modal.msgError('查询失败，请稍后重试');
          })
          .finally(() => {
            this.loading2 = false;
          });
    }
  }
}
</script>

<style lang="scss" scoped>
.stock-container {
  min-height: 100vh;
  background-color: #f8f9fa;
  padding: 16px;
}

.search-form {
  background-color: #fff;
  border-radius: 8px;
  padding: 16px;

  .form-item {
    margin-bottom: 16px;

    .label {
      display: block;
      font-size: 14px;
      color: #333;
      margin-bottom: 8px;
      font-weight: 500;

      .required {
        color: #ff4d4f;
        margin-left: 4px;
      }
    }

    .input-wrapper {
      position: relative;
      display: flex;
      align-items: center;
    }

    .input {
      width: 100%;
      height: 40px;
      background-color: #f8f9fa;
      border-radius: 4px;
      padding: 0 12px;
      font-size: 14px;
      color: #333;
    }

    .clear-btn {
      position: absolute;
      right: 12px;
      font-size: 18px;
      color: #999;
      cursor: pointer;
      line-height: 1;
      z-index: 10;
      
      &:hover {
        color: #666;
      }
    }
  }
}

.btn-group {
  display: flex;
  justify-content: space-between;
  margin-top: 24px;

  .btn {
    width: 48%;
    height: 40px;
    border-radius: 4px;
    font-size: 14px;
    font-weight: 500;

    &.btn-default {
      background-color: #f8f9fa;
      color: #666;
    }

    &.btn-primary {
      background-color: #4A90E2;
      color: #fff;

      &:disabled {
        opacity: 0.7;
      }
    }
  }
}

.stock-list {
  margin-top: 16px;
  background-color: #fff;
  border-radius: 8px;
  overflow: hidden;

  .stock-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px;
    background-color: #f8f9fa;
    border-bottom: 1px solid #e8e8e8;

    .material-code {
      font-size: 16px;
      font-weight: 600;
      color: #333;
    }

    .quantity {
      font-size: 16px;
      color: #4A90E2;
      font-weight: 600;
    }
  }

  .stock-table {
    width: 100%;
    overflow-x: auto;
    background: #fff;
    
    .table-header {
      display: flex;
      background-color: #fafafa;
      border-bottom: 2px solid #e8e8e8;
      position: sticky;
      top: 0;
      z-index: 10;

      .header-cell {
        font-weight: 600;
        color: #333;
        background-color: #fafafa;
      }
    }

    .table-body {
      .table-row {
        display: flex;
        border-bottom: 1px solid #f0f0f0;
        
        &:hover {
          background-color: #f8f9fa;
        }
      }
    }

    .table-cell {
      padding: 8px 6px;
      font-size: 12px;
      color: #333;
      border-right: 1px solid #f0f0f0;
      display: flex;
      align-items: center;
      min-height: 40px;
      
      // 关键：防止文本溢出
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      
      &:last-child {
        border-right: none;
      }
      
      // 精确控制各列宽度
      &.barcode-col {
        flex: 0 0 120px;
        min-width: 160px;
        max-width: 160px;
      }
      
      &.material-col {
        flex: 0 0 100px;
        min-width: 100px;
        max-width: 100px;
      }
      
      &.box-col {
        flex: 0 0 80px;
        min-width: 80px;
        max-width: 80px;
      }
      
      &.location-col {
        flex: 0 0 70px;
        min-width: 70px;
        max-width: 70px;
      }
      
      &.batch-col {
        flex: 0 0 80px;
        min-width: 80px;
        max-width: 80px;
      }
      
      &.task-col {
        flex: 0 0 90px;
        min-width: 90px;
        max-width: 90px;
      }
      
      &.pallet-col {
        flex: 0 0 80px;
        min-width: 80px;
        max-width: 80px;
      }
      
      &.status-col {
        flex: 0 0 70px;
        min-width: 70px;
        max-width: 70px;
        justify-content: center;
      }
      
      &.time-col {
        flex: 0 0 90px;
        min-width: 90px;
        max-width: 90px;
      }
      
      &.action-col {
        flex: 0 0 60px;
        min-width: 60px;
        max-width: 60px;
        justify-content: center;
        // 操作列不需要文本截断
        white-space: normal;
      }
    }
    
    .status-tag {
      padding: 2px 6px;
      border-radius: 3px;
      font-size: 10px;
      color: #fff;
      
      &.status-pending {
        background-color: #faad14;
      }
      
      &.status-success {
        background-color: #52c41a;
      }
      
      &.status-error {
        background-color: #ff4d4f;
      }
      
      &.status-warning {
        background-color: #fa8c16;
      }
      
      &.status-default {
        background-color: #d9d9d9;
        color: #666;
      }
    }
    
    .action-btn {
      padding: 4px 8px;
      border-radius: 3px;
      font-size: 10px;
      border: none;
      cursor: pointer;
      white-space: nowrap;
      
      &.off-shelf-btn {
        background-color: #ff4d4f;
        color: #fff;
        
        &:hover {
          background-color: #ff7875;
        }
        
        &:active {
          background-color: #d9363e;
        }
      }
    }
  }
}

.empty-state {
  margin-top: 16px;
  padding: 32px;
  text-align: center;
  background-color: #fff;
  border-radius: 8px;

  .empty-text {
    font-size: 14px;
    color: #999;
  }
}

.iconfont-spin {
  display: inline-block;
  animation: loading-rotate 2s linear infinite;
}

@keyframes loading-rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>


